<template>
  <div id="vedio">
    <room-container ref="TUIRoomRef"></room-container>
  </div>
</template>

<script lang="ts">
import RoomContainer from "@/TUIRoom/index.vue";
import Vue from "vue";
import axios from "axios";
import { Message, Loading } from "element-ui";
import { TuiRoomInitParam } from "@/TuiRoomParams.ts";

export default Vue.extend({
  components: {
    RoomContainer,
  },
  data() {
    return {};
  },
  async mounted() {
    if (!this.$route.query.user) {
      Message.error('没有用户ID传入不可创建视频')
      return 
    }
    const loadingInstance = Loading.service({
      lock: true,
      text: "正在创建房间",
      spinner: "el-icon-loading",
      background: "rgba(255, 255, 255, 0.3)",
    });
    try {
      const initParam: typeof TuiRoomInitParam & {roomId: number} = await this.getUserSig(this.$route.query.user as string)
      if (!initParam) return
      const temp: any = this.$refs?.TUIRoomRef;
      // 初始化 TUIRoom 组件
      await temp?.init?.(initParam);
      // 默认执行创建房间
      await this.handleCreateRoom(initParam.roomId);
    } catch(error: any) {
      Message.error(error.message);
    } finally {
      loadingInstance.close()
    }
    
  },
  methods: {
    async getUserSig(userId: string): Promise<typeof TuiRoomInitParam | false> {
      const response = await axios({
        method: "post",
        url: "/admin/getTencentUserSig",
        data: { userId, type: "admin" },
      })
      if (response.status !== 200 && response.statusText !== 'OK') {
        throw new Error('请求错误')
      }
      const { code, data } = response.data
      if (code !== 200) {
        throw new Error(data)
      }
      return data
    },
    // 主持人创建房间，该方法只在创建房间时调用
    async handleCreateRoom(roomId: number) {
      const roomMode = "FreeSpeech";
      const roomParam = {
        isOpenCamera: true,
        isOpenMicrophone: true,
      };
      const temp: any = this.$refs?.TUIRoomRef;
      await temp.createRoom(roomId, roomMode, roomParam);
    },
  },
});
</script>

<style>
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

#vedio {
  width: 100%;
  height: 100%;
}
</style>
